<template>
	<div class="job-information-list">
		<go-back title="工作流程管理" />
		<!--<zk-searcher v-model="query" :options="searchColumns" />-->
		<w-block class="body" title="任务配置" style="margin-top: 10px">
			<template #list>
				<div v-if="canEdit" class="btn-list">
					<el-button class="btn-list-item" type="primary" @click="handleAdd({'rel_work_id':routeId})">增加</el-button>
					<el-button class="btn-list-item" type="warning" @click="handleUpdate({'rel_work_id':routeId})">修改</el-button>
					<el-button class="btn-list-item" type="danger" @click="handleDelete">删除</el-button>
				</div>
				<div v-else class="text-info"> 启动的模版不可编辑</div>
			</template>
			<zk-table
				ref="zkTable"
				:columns="tableColumns"
				:service="service"
				:query="query"
				use-selection
				:usePagination="false"
				:actions="actions"
				:requestInterceptor="requestInterceptor"
				@onSelectionChange="onSelection"
				@doOtherAction="doActions"
			>
				<template #sp_level="scope">
					<div style="text-align: center">
						<el-link v-if="scope.row.sp_level" type="primary" @click="handleLookApproverList(scope)">
							<i class="fs-25 cursor-pointer el-icon-s-custom"></i>
						</el-link>
					</div>
				</template>
				<template #control="scope">
					<el-button
						type="primary"
						icon="el-icon-upload2"
						circle
						@click="updateOrder(scope.row,scope.index,true)"
						:disabled="!canEdit || scope.index === 0"
					></el-button>
					<el-button
						type="primary"
						icon="el-icon-download"
						circle
						@click="updateOrder(scope.row,scope.index,false)"
						:disabled="!canEdit || showButtonDown(scope.index)"
					></el-button>
				</template>
			</zk-table>
		</w-block>
		<w-dialog :visible.sync="visible" height="auto" :title="modalTitle" width="1200px" v-if="oTaskListOnPage.length">
			<el-form ref="modelForm" :model="model" label-width="160px">
				<div class="form-box">
					<el-row class="flex-1">
						<el-col v-for="item of asyncFormColumns" :key="item.key" :span="item.span || 22">
							<el-form-item
								:label="item.label"
								:prop="item.key"
								:rules="item.required && [{ required: true, message: `请输入${item.label}`, trigger: ['blur'] }]"
							>
								<zk-item-pool
									style="width: 218px;"
									v-model="model[item.key]"
									:option="{...item, disabled:item.disabled }"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="20" :offset="3">
							<el-button type="primary" @click="addApprovedLevel">添加审批层级</el-button>
						</el-col>
						<el-col class="mt-20" :span="20" :offset="3" v-for="(item, i) in approverList" :key="i">
							<el-divider content-position="left">
								<el-button
									type="success"
									round
									icon="el-icon-plus"
									@click="getApprover(i)">
									添加{{i+1}}级审批人
								</el-button>
								<el-button
									type="default"
									round
									icon="el-icon-minus"
									@click="delApprover(i)">
									删除当前审批层级
								</el-button>
							</el-divider>
							<div class="approver-box">
								<el-button
									class="mt-20"
									v-for="(innerItem , j) in item.list"
									:key="j"
									type="default"
									round
									icon="el-icon-user">
									{{innerItem.label}}
								</el-button>
							</div>
						</el-col>
					</el-row>
					<div style="width:300px">
						<el-button @click="resetChecked">清空</el-button>
						<el-tree
							:key="treeKey"
							class="mt-10"
							ref="tree"
							:data="treeData"
							show-checkbox
							node-key="id"
							:default-expanded-keys="[]"
							:default-checked-keys="[]"
							:props="defaultProps"
						/>
					</div>
				</div>
			</el-form>
			<template #footer>
				<div class="flex-end">
					<el-button type="default" @click="visible=false">取 消</el-button>
					<el-button type="primary" @click="submit">保 存</el-button>
				</div>
			</template>
		</w-dialog>
		<w-dialog :visible.sync="visibleLookApproverList" height="auto" title="查看审批层级" width="600px">
			<el-row>
				<el-col class="!mt-20" :span="20" :offset="3" v-for="(item, i) in approverList" :key="i">
					<el-divider content-position="left" style="min-width: 300px">{{i+1}}级审批人</el-divider>
					<div class="approver-box">
						<el-button
							class="mt-20"
							v-for="(innerItem , j) in item.list"
							:key="j"
							type="default"
							round
							icon="el-icon-user">
							{{innerItem.label}}
						</el-button>
					</div>
				</el-col>
			</el-row>
			<template #footer>
				<div class="flex-end">
					<el-button type="default" @click="handleClosedLookApproverList">关 闭</el-button>
				</div>
			</template>
		</w-dialog>
	</div>
</template>
<script>
import { TYPE_ENUM }                    from '@/common/zk-constants'
import { taskConfiguration as service } from '@/services'
import SearchTableCRUDMixin             from '@/mixins/search-table-crud-mixin'
import GoBack                           from '@/components/go-back'
import api                              from '@/api/api'

const actions = ['slot', 200]

const columns = [
	{ label: '选择任务', key: 'task_code', form: true, type: TYPE_ENUM.SELECT, options: [] },
	{ label: '任务编号', key: 'task_code', table: true },
	{ label: '任务序号', key: 'ord', table: true, },
	{ label: '任务编号', key: '_task_code', form: true, disabled: true },
	{ label: '任务名称', key: 'task_name', table: true, },
	{ label: '所需上传要件', key: 'item_name', table: true, form: true, disabled: true },
	{ label: '完成时限', key: 'dur_time', table: true, form: true, type: TYPE_ENUM.NUMBER },
	{
		label   : '责任部门',
		key     : 'duty_dept',
		table   : true,
		form    : true,
		type    : TYPE_ENUM.SELECT,
		storeKey: 'orgList',
		required: true
	},
	{
		'label': '是否审批',
		'key'  : 'sp_level',
		table  : true,
		slot   : true,
	}
]

export default {
	mixins    : [SearchTableCRUDMixin],
	components: { GoBack },
	data() {
		return {
			routeId                : this.$route.params.id,
			service,
			columns,
			actions,
			oTaskListOnPage        : [],
			asyncFormColumns       : [],
			defaultProps           : {
				children: 'children',
				label   : 'label'
			},
			canEdit                : !JSON.parse(sessionStorage.templateIsStart || 1),
			treeData               : [
				/*{
					id        : 2,
					label     : '技术规划部',
					levelState: 2,
					children  : [
						{
							id        : 5,
							label     : '王勤',
							levelState: 1,
						},
						{
							id        : 55,
							label     : '蔡璐',
							levelState: 1,
						},
					]
				},*/
			],
			approverList           : [
				/*{
					list: [
						{
							id            : 1,
							label         : "管理员",
							levelState    : "1",
							sp_dept       : "7825",
							sp_dept_name  : "技术规划部",
							sp_person_id     : "1",
							sp_person_name: "管理员"
						}
					]
				},*/
			],
			visibleLookApproverList: false,
			treeKey                : 0
		}
	},
	computed  : {
		modalTitle() {
			return this.isAddModal ? '添加' : '编辑'
		},
	},
	watch     : {
		'model.task_code'(e) {
			const task = this.oTaskListOnPage.find(item => item.task_code === e)
			if (task) {
				console.log(task)
				const { seleTask, id, task_code, item_name } = task

				this.model = { ...this.model, seleTask, rel_sz: id, task_code, _task_code: task_code, item_name }
			}
		},
		oTaskListOnPage(newList) {
			const [first] = columns
			first.options = newList
			this.asyncFormColumns = columns.filter(e => e.form)
		},
		visible(newValue) {
			if (!newValue) {
				this.approverList = []
				this.$refs.tree.setCheckedKeys([])
				++this.treeKey
			}
		}
	},
	methods   : {
		handleAdd(model = {}) {
			if (!this.oTaskListOnPage.length) {
				this.$message.warning('没有任务,需要在任务设置里增加任务')
				return
			}
			this.isAddModal = true
			this.model = model
			this.visible = true
		},
		requestInterceptor(query) {
			return { ...query, 'rel_work_id': this.routeId }
		},
		async updateOrder(row, index, isUp) {
			// console.log(row, index, isUp)
			// console.log(this.$refs.zkTable.$data.tableData)
			var qian_id = row.id
			var qian_idx = ''
			var hou_id = ''
			var hou_idx = row.ord
			if (isUp == true) {
				hou_id = this.$refs.zkTable.$data.tableData[index - 1].id
				qian_idx = this.$refs.zkTable.$data.tableData[index - 1].ord
			}
			else if (isUp == false) {
				hou_id = this.$refs.zkTable.$data.tableData[index + 1].id
				qian_idx = this.$refs.zkTable.$data.tableData[index + 1].ord
			}

			await api.post['/rest/rptTask/changeTaskIndex'](qian_id, hou_id, qian_idx, hou_idx)
				.then(({ data }) => {
					if (!data) {
						return
					}
					//表格刷新
					this.reload()
					this.$message({
						message: '移动成功',
						type   : 'success'
					})
				})
		},
		//禁用最后一条数据的下调按钮
		showButtonDown(index) {
			var number = this.$refs.zkTable.$data.total - 1
			if (index == number) {
				return true
			}
			else if (index != number) {
				return false
			}
		},
		doActions() {

		},
		resetChecked() {
			this.$refs.tree.setCheckedKeys([])
		},
		addApprovedLevel() {
			this.approverList.push({ list: [] })
		},
		getApprover(i) {
			// console.log('i', i);
			console.log(this.$refs.tree.getCheckedNodes())   //取node
			// console.log(this.$refs.tree.getCheckedKeys()); //还能取key

			this.approverList[i].list = this.$refs.tree.getCheckedNodes().filter(item => item['levelState'] == 1)
		},
		delApprover(i) {
			this.approverList.splice(i, 1)
			++this.treeKey
		},
		handleUpdate(model = {}) {
			this.isAddModal = false
			if (this.selectedRows.length === 1) {
				let [selected = {}] = this.selectedRows
				if (selected.id) {

					this.approverList = this._str2ApproverList(selected)

					this.model = { ...selected, ...model }
					this.visible = true
				}
			}
			else if (this.selectedRows.length === 0) {
				this.$message.warning('请选择要编辑的记录')
			}
			else {
				this.$message.warning('请选择唯一一条记录')
			}
		},
		async submit() {
            // console.log(this.model)
            if(this.model.dur_time <= 0){
                this.$message({
                message: "完成时限需大于0",
                type: "warning",
              });
              return;
            }
			this.$refs.modelForm.validate(async (valid) => {
				if (valid) {
					//将this.approverList转成sp_level:'1;1;2;2;3'
					if (this.approverList.length) {
						let sp_person_id = []
						let sp_person_name = []
						let sp_level = []
						let sp_dept_id = []
						let sp_dept_name = []

						this.approverList.forEach((item, i) => {
							item.list.forEach(innerItem => {
								sp_person_id.push(innerItem.sp_person_id)
								sp_person_name.push(innerItem.sp_person_name)
								sp_level.push(i + 1)
								sp_dept_id.push(innerItem.sp_dept_id)
								sp_dept_name.push(innerItem.sp_dept_name)
							})
						})
						// 有审批树流程, 要混入审批的参数
						Object.assign(this.model, {
							sp_person_id  : sp_person_id.join(';'),
							sp_person_name: sp_person_name.join(';'),
							sp_level      : sp_level.join(';'),
							sp_dept_id    : sp_dept_id.join(';'),
							sp_dept_name  : sp_dept_name.join(';'),
						})
					} else {
            Object.assign(this.model, {
              sp_person_id  : '',
              sp_person_name: '',
              sp_level      : '',
              sp_dept_id    : '',
              sp_dept_name  : '',
            })
          }
					let ret = null
					if (this.isAddModal) {
						delete this.model.id
						ret = await this.service.addItem(this.model)
					}
					else {
						ret = await this.service.editItem(this.model)
					}
					if(ret){
					  this.reload()
						this.model = {}
						this.visible = false
						this.approverList = []
						this.resetChecked()
					}
				}
			})
		},
		handleLookApproverList({ row, index }) {
			// console.log(row, index);
			this.visibleLookApproverList = true
			this.approverList = this._str2ApproverList(row)
		},
		handleClosedLookApproverList() {
			this.visibleLookApproverList = false
			this.approverList = []
		},
		_str2ApproverList(row) {
			if (!row) return []

			//将sp_level:'1;1;2;2;3'转成this.approverList
			if (
				row.hasOwnProperty('sp_level') &&
				row.hasOwnProperty('sp_person_id') &&
				row.hasOwnProperty('sp_person_name') &&
				row.hasOwnProperty('sp_dept_id') &&
				row.hasOwnProperty('sp_dept_name')
			) {
				const approverList = []
				const sp_level = row.sp_level.split(',')
				const sp_person_id = row.sp_person_id.split(',')
				const sp_person_name = row.sp_person_name.split(',')
				const sp_dept_id = row.sp_dept_id.split(',')
				const sp_dept_name = row.sp_dept_name.split(',')
				//先把审批层级加上
				for (let i = 0; i < sp_level[sp_level.length - 1]; i++) {
					approverList.push({ list: [] })
				}
				//再通过 row.sp_level 算出想要的 approverList
				for (let i = 0; i < sp_level.length; i++) {
					approverList[sp_level[i] - 1].list.push({
						sp_person_id  : sp_person_id[i],
						sp_person_name: sp_person_name[i],
						sp_dept_id    : sp_dept_id[i],
						sp_dept_name  : sp_dept_name[i],
						label         : sp_person_name[i],
					})

				}
				return approverList
			}
			return []
		},
	},
	async mounted() {
		this.oTaskListOnPage = await service.queryTaskList_sz_unpagi()
		const { data: { data: treeData } } = await api.get['/rest/rptSp/querySpPersonTree']()
		this.treeData = treeData
	},
}
</script>
<style scoped lang="scss">
	@import "~@/assets/css/_variables.scss";

	.circle-btn {
		background: rgb(60, 144, 204);
		width: 40px;
		height: 40px;
		border-radius: 50%;
		display: inline-block;
		margin: 0 10px;
		cursor: pointer;
		filter: grayscale(.3);

		&:hover {
			filter: grayscale(0);
		}

		i {
			color: white;
			font-size: 30px;
		}
	}

	.form-box {
		@include space-between(flex-start);
	}

	.approver-box {
		width: 100%;
		@include flex-start(flex-start);
		flex-wrap: wrap;
	}
	.el-divider--horizontal {
		min-width: 140px;
	}
</style>
